$(function () {
	var id = sessionStorage.getItem("id");
	var token = sessionStorage.getItem("token");

	$("form").on("submit", function (e) {
		e.preventDefault(); // 阻止表单的默认提交行为
		var oldpassword = $(".oldpassword").val();
		var newpassword = $(".newpassword").val();
		var rnewpassword = $(".rnewpassword").val();

		// 正则表达式验证密码
		const password_pattern = /\w{6,12}/;

		if (!newpassword === rnewpassword) {
			alert("两次输入的新密码不匹配。");
			return false;
		}

		if (!password_pattern.test(newpassword)) {
			alert("新密码格式错误，密码必须为6-12位字母或数字。");
			return false;
		}

		axios
			.post(
				`http://localhost:9000/users/rpwd`,
				{
					id: id,
					oldPassword: oldpassword,
					newPassword: newpassword,
					rNewPassword: rnewpassword,
				},
				{
					headers: {
						authorization: token,
					},
				}
			)
			.then(function (response) {
				if (response.data.code === 1) {
					$('.error').text(response.data.message).show();
					sessionStorage.clear(); // 从 sessionStorage 中移除用户信息
					window.location.href = "./login.html";
				} else {
					$('.error').text(response.data.message).show(); 
				}
			})

		return false; // 阻止表单提交
	});
});
